package com.loongtech.bi.manager.system;

import com.loongtech.bi.dao.CommonDao;
import com.loongtech.bi.entity.POJO.Page;
import com.loongtech.bi.entity.POJO.PojoMonitorResult;
import com.loongtech.bi.entity.system.EntityMonitorResult;
import com.loongtech.core.jpa.manager.ManagerBase;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class BiMonitorResultManager extends ManagerBase<EntityMonitorResult> {

	private static final long serialVersionUID = 1L;
    @Resource
    private CommonDao commonDao;

	/**
	 * 获取所有告警
     *
	 */
	public List<EntityMonitorResult> queryList() {
        return findByQuery("from EntityMonitorResult order by creatTime desc");
	}

	/**
	 * 查询告警（JSF）
	 */
	public List<EntityMonitorResult> searchByCriteria(Date dateStart, Date dateEnd) {
		List<Object> list = new ArrayList<>();
		StringBuilder hql = new StringBuilder(" from EntityMonitorResult e where 1=1 ");
		hql.append(" and creatTime >= ?");
		list.add(dateStart.getTime());
		hql.append(" and creatTime <= ?");
		list.add(dateEnd.getTime());
		hql.append(" order by e.creatTime desc");

		return findByQuery(hql.toString(), list.toArray());
	}

    /**
     * 查询告警(springmvc)
     */
	public Page< List<PojoMonitorResult>> queryByCriteria(Integer curPage, Integer pageSize, Date dateStart, Date dateEnd){
        String sql = "select e.jobId, e.result, e.userOrGroupName, e.serverId, e.creatTime, c.description, c.subDescription from bi_monitor_result e, bi_monitor_config c where e.jobId = c.id and e.creatTime >= ? and e.creatTime <= ? order by e.creatTime desc limit ? , ?";
        List<PojoMonitorResult> list = commonDao.queryObjList(sql, new Object[]{dateStart.getTime(), dateEnd.getTime(), (curPage - 1) * pageSize, pageSize}, PojoMonitorResult.class);
        String sql2 = "select count(1) from bi_monitor_result e, bi_monitor_config c where e.jobId = c.id and e.creatTime >= ? and e.creatTime <= ?";
        Integer totalSize = commonDao.queryForInt(sql2, new Object[]{dateStart.getTime(), dateEnd.getTime()});
        return new Page<>(list, totalSize, curPage, pageSize);
    }
}
